import pydicom
from pydicom.sequence import Sequence


def extract_sequence_structure(file_path):
    """提取DICOM文件中的序列结构"""
    ds = pydicom.dcmread(file_path)

    def parse_element(elem, path="", level=0):
        """递归解析元素结构"""
        current_path = f"{path}.{elem.keyword}" if path else elem.keyword
        tagId = f"({elem.tag.group:04X},{elem.tag.element:04X})"
        if tagId == '(7FE0,0010)':
            return None

        element_info = {
            'tagId':tagId ,
            'description': elem.name,
            'children': []
        }


        # 如果是序列，处理其子元素
        if elem.VR == 'SQ':
            for item_idx, item in enumerate(elem.value):
                children = []
                for sub_elem in item:
                    child_info = parse_element(sub_elem, current_path, level + 1)
                    if child_info is not None:
                        children.append(child_info)
                element_info['children'] = children
        else:
            element_info['value'] = str(elem.value)[:100]

        return element_info

    # 解析所有顶级元素
    structure = []
    for elem in ds:
        structure.append(parse_element(elem))

    return structure


# def print_structure(structure, show_values=True):
#     """打印结构化的DICOM数据"""
#
#     def print_element(elem_info, indent=""):
#         print(f"{indent}├─ {elem_info['name']} ({elem_info['tag_hex']})")
#         print(f"{indent}│  VR: {elem_info['VR']}, Keyword: {elem_info['keyword']}")
#
#         if elem_info['is_sequence']:
#             print(f"{indent}│  Sequence with {elem_info['sequence_length']} item(s)")
#             for item_idx, item in enumerate(elem_info['children']):
#                 print(f"{indent}│  └─ Item {item_idx + 1}:")
#                 for sub_elem in item['elements']:
#                     print_element(sub_elem, indent + "│      ")
#         else:
#             if show_values:
#                 value = elem_info['value'][:100] + "..." if len(elem_info['value']) > 100 else elem_info['value']
#                 print(f"{indent}│  Value: {value}")
#         print(f"{indent}│")
#
#     for elem in structure:
#         print_element(elem)


# 使用示例
structure = extract_sequence_structure('D:\\test\\py_test_path3\\SYNO0001.dcm')
print(structure)
